package com.member.mp.web.user;

import cn.binarywang.wx.miniapp.api.WxMaSecCheckService;
import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaCodeLineColor;
import com.alibaba.fastjson2.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.member.common.constant.HttpStatus;
import com.member.common.constant.SystemConst;
import com.member.common.core.page.PageDomain;
import com.member.common.core.page.TableDataInfo;
import com.member.common.core.page.TableSupport;
import com.member.common.utils.DateUtils;
import com.member.common.utils.PageUtils;
import com.member.common.utils.StringUtils;
import com.member.common.utils.sql.SqlUtil;
import com.member.framework.web.domain.server.Sys;
import com.member.mp.config.WxMaConfiguration;
import com.member.shop.domain.SysBizTenant;
import com.member.shop.domain.SysBizUser;
import com.member.shop.mapper.SysBizUserMapper;
import com.member.shop.service.ISysBizTenantService;
import com.member.shop.service.ISysBizUserService;
import com.member.shop.service.impl.SysBizUserServiceImpl;
import com.member.system.cache.CommonCache;
import com.member.system.cache.TokenCache;
import me.chanjar.weixin.common.error.WxErrorException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import sun.misc.BASE64Encoder;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.beans.PropertyEditorSupport;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.List;

/**
 * @author wangxin
 * @Description
 * @date 2024/2/28 13:14
 **/
public class SupperController {
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 将前台传递过来的日期格式的字符串，自动转化为Date类型
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        // Date 类型转换
        binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) {
                setValue(DateUtils.parseDate(text));
            }
        });
    }

    /**
     * 设置请求分页数据
     */
    protected void startPage() {
        PageUtils.startPage();
    }

    /**
     * 设置请求排序数据
     */
    protected void startOrderBy() {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        if (StringUtils.isNotEmpty(pageDomain.getOrderBy())) {
            String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
            PageHelper.orderBy(orderBy);
        }
    }

    /**
     * 清理分页的线程变量
     */
    protected void clearPage() {
        PageUtils.clearPage();
    }

    /**
     * 响应请求分页数据
     */
    @SuppressWarnings({"rawtypes", "unchecked"})
    protected TableDataInfo getDataTable(List<?> list) {
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(list);
        rspData.setTotal(new PageInfo(list).getTotal());
        return rspData;
    }

    @SuppressWarnings({"rawtypes", "unchecked"})
    protected TableDataInfo getDataList(List<?> list) {
        TableDataInfo rspData = new TableDataInfo();
        rspData.setList(list);
        rspData.setTotal(new PageInfo(list).getTotal());
        return rspData;
    }

    public HttpServletRequest getRequest() {
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        assert ra != null;
        return ((ServletRequestAttributes) ra).getRequest();
    }

    public String getToken() {
        return this.getRequest().getHeader(SystemConst.TOKEN);
    }

    /**
     * 获取用户缓存信息
     */
    public SysBizUser getLoginUser() {
        String token2 = this.getRequest().getHeader(SystemConst.TOKEN);
        if (StringUtils.isBlank(token2)) {
//
//            SysBizUser sysBizUser = new SysBizUser();
//            sysBizUser.setId(180L);
//            sysBizUser.setTenantId(1L);
//            sysBizUser.setNickName("疯狂摇摇冻\uD83E\uDD2A");
//            sysBizUser.setScore(180L);
//            return sysBizUser;

            return null;
        }
        String token = token2.replaceAll("Bearer ", StringUtils.EMPTY);
        logger.info("token:" + token);
        return getLoginUser(token);
    }

    @Resource
    private ISysBizTenantService tenantService;

    /**
     * 获取登录用户id
     */
    public Long getUserId() {
        if(getLoginUser() == null){
            return 0L;
        }
        return getLoginUser().getId();
    }

    @Resource
    private SysBizUserMapper sysBizUserMapper;

    public Long getTenantId() {

        String tenant = this.getRequest().getHeader(SystemConst.DEFAULT_TENANT);
        SysBizUser loginUser = getLoginUser();
        if (loginUser != null) {
            //用户id
            Long id = loginUser.getId();
            //防止认证通过后token有延迟
            SysBizUser byId = sysBizUserMapper.selectSysBizUserById(id);
            if (byId == null) {
                return byId.getTenantId();
            }
        }

        if (StringUtils.isNotEmpty(tenant)) {
            return Long.parseLong(tenant);
        }
        if (tenantService != null) {
            SysBizTenant tenantByDefault = tenantService.selectSysBizTenantByDefault();
            logger.info("获取默认站点");
            return tenantByDefault.getId();
        }

        return null;


    }

    /**
     * 获取登录用户名
     */
    public String getUsername() {
        return getLoginUser().getNickName();
    }

    public String getUserPhone() {
        return getLoginUser().getUserPhone();
    }

    public SysBizUser getLoginUser(String token) {
        String data = TokenCache.getMpData(token);
        if (StringUtils.isEmpty(data)) {
            return null;
        }
        return JSON.parseObject(data, SysBizUser.class);
    }

    /**
     * 获取请求的公网ip
     */
    public static String getIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {
            // 多次反向代理后会有多个ip值，第一个ip才是真实ip
            int index = ip.indexOf(",");
            if (index != -1) {
                return ip.substring(0, index);
            } else {
                return ip;
            }
        }
        ip = request.getHeader("X-Real-IP");
        if (StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {
            return ip;
        }
        return request.getRemoteAddr();
    }

    /**
     * 修改为2.0版本敏感词过滤，可自定义配置敏感词
     *
     * @param message
     * @param openId
     * @return
     */
    public boolean checkMessage(String message, String openId) {
        try {
            String appid = "wxeb1ae3859efb0741";
            final WxMaService wxService = WxMaConfiguration.getMaService(appid);
            WxMaSecCheckService secCheckService = wxService.getSecCheckService();
            JsonObject jsonObject = new JsonObject();
            // 版本
            jsonObject.addProperty("version", 2);
            jsonObject.addProperty("openid", openId);
            // 场景枚举值（1 资料；2 评论；3 论坛；4 社交日志）
            jsonObject.addProperty("scene", 2);
            jsonObject.addProperty("content", message);

            String post = wxService.post("https://api.weixin.qq.com/wxa/msg_sec_check", jsonObject.toString());
            Gson gson = new Gson();
            JsonObject response = gson.fromJson(post, JsonObject.class);
            JsonElement jsonResult = response.get("result").getAsJsonObject().get("label");
            /*
              命中标签枚举值，100 正常；
              10001 广告；
              20001 时政；
              20002 色情；
              20003 辱骂；
              20006 违法犯罪；
              20008 欺诈；
              20012 低俗；
              20013 版权；
              21000 其他
             */
            return jsonResult.getAsInt() == 100;
        } catch (WxErrorException e) {
            return false;
        }

    }

    public String genCode(String data, String path) {
        String appid = "wx6d217bde10c11f08";
        final WxMaService wxService = WxMaConfiguration.getMaService(appid);
        try {
            byte[] releases = wxService.getQrcodeService().createWxaCodeUnlimitBytes(data, path, true, "release", 430, true, null, false);
            BASE64Encoder base64Encoder = new BASE64Encoder();
            // 得到文件 之后转成beye 然后使用base64转码
            return base64Encoder.encode(releases);
        } catch (WxErrorException e) {
            e.printStackTrace();
        }
        return null;
    }
}
